import frappe


@frappe.whitelist(methods=["POST"])
def set_user_language(language: str):
    """Persist and apply current user's language immediately.

    - Update `User.language`
    - Clear user cache to refresh boot info
    - Set session language in-memory for current request
    """
    user = frappe.session.user
    if not user or user == "Guest":
        frappe.throw("Login required")

    # normalize short codes
    lang = (language or "en").strip()

    # persist on User doctype
    frappe.db.set_value("User", user, "language", lang)

    # clear caches so next boot picks up the new lang
    frappe.clear_cache(user=user)

    # apply to current session immediately
    frappe.local.lang = lang
    frappe.session.lang = lang
    return {"ok": True, "lang": lang}



@frappe.whitelist(methods=["GET"], allow_guest=False)
def get_user_roles():
    """Return current user's roles list."""
    user = frappe.session.user
    return frappe.get_roles(user)


@frappe.whitelist(methods=["GET", "POST"], allow_guest=True)
def logout_to_flowa():
    """Log out current session and redirect to /flowa/login."""
    try:
        if getattr(frappe.local, 'login_manager', None):
            frappe.local.login_manager.logout()
        else:
            from frappe.auth import LogoutManager  # type: ignore
            LogoutManager()
    except Exception:
        pass
    try:
        frappe.response['sid'] = ''  # clear cookie
    except Exception:
        pass
    frappe.local.response['type'] = 'redirect'
    frappe.local.response['location'] = '/flowa/login'

